<template>
  <div class="doc-management">
    <div class="header">
      <a-input-search
          v-model:value="searchText"
          placeholder="请输入文档名称"
          @search="handleSearch"
          class="search-input"
      />
      <a-button type="primary" @click="addDoc" class="add-button">
        新增文档
      </a-button>
    </div>
    <div class="content">
      <a-tree
          :tree-data="displayCategories"
          :field-names="fieldNames"
          :selectable="false"
          default-expand-all
      >
        <template #title="{ name, id }">
          <span class="doc-name">{{ name }}</span>
          <span class="actions">
            <a-button type="link" @click="editDoc(id)">编辑</a-button>
            <a-button type="link" @click="deleteDoc(id)">删除</a-button>
          </span>
        </template>
      </a-tree>
    </div>

    <a-modal
        v-model:visible="editModalVisible"
        :title="editModalTitle"
        @ok="handleEditOk"
        @cancel="handleModalCancel"
        :destroy-on-close="false"
    >
      <a-form
          ref="editFormRef"
          :model="editForm"
          :rules="editFormRules"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
      >
        <a-form-item label="名称" name="name">
          <a-input v-model:value="editForm.name" />
        </a-form-item>
        <a-form-item label="内容" name="content">
          <a-textarea v-model:value="editForm.content" :rows="4" />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, computed, onMounted, nextTick } from 'vue';
import axios from 'axios';
import { useRoute } from "vue-router";

export default defineComponent({
  setup() {
    const route = useRoute();
    const categories = ref([]);
    const docTree = ref([]);
    const searchText = ref('');
    const editModalVisible = ref(false);
    const editModalTitle = ref('');
    const editForm = ref({});
    const editFormRef = ref(null);

    const fieldNames = {
      children: 'children',
      title: 'name',
      key: 'id',
    };

    const editFormRules = {
      name: [{ required: true, message: '请输入文档名称' }],
    };

    const fetchData = async () => {
      try {
        const ebookId = route.query.ebookId;
        if (!ebookId) {
          console.error("ebookId 未找到");
          return;
        }
        const url = `/doc/all?ebookId=${ebookId}`;

        const response = await axios.get(url);
        categories.value = response.data.content;

        console.log('categories', categories);
        docTree.value = buildDocTree(response.data.content);
      } catch (error) {
        console.error('Failed to fetch data:', error);
      }
    };

    const buildDocTree = (categories) => {
      const map = new Map();
      const roots = [];

      categories.forEach((doc) => {
        map.set(doc.id, {
          ...doc,
          children: [],
        });
        if (doc.parent === 0) {
          roots.push(map.get(doc.id));
        }
      });

      categories.forEach((doc) => {
        if (doc.parent !== 0) {
          const parentDoc = map.get(doc.parent);
          if (parentDoc) {
            parentDoc.children.push(map.get(doc.id));
          }
        }
      });

      return roots;
    };

    const displayCategories = computed(() => {
      const filterCategories = (categories, keyword) => {
        return categories.filter((doc) => {
          if (doc.name.includes(keyword)) {
            return true;
          }
          if (doc.children) {
            doc.children = filterCategories(doc.children, keyword);
            return doc.children.length > 0;
          }
          return false;
        });
      };

      return searchText.value
          ? filterCategories(docTree.value, searchText.value)
          : docTree.value;
    });

    const handleSearch = () => {
      // No need to refetch data, computed property will handle filtering
    };

    const addDoc = () => {
      const ebookId = route.query.ebookId;
      if (!ebookId) {
        console.error("ebookId 未找到");
        return;
      }
      editForm.value = {
        name: '',
        content: '',
        ebookId: ebookId,
      };
      editModalTitle.value = '新增文档';
      editModalVisible.value = true;
    };

    const fetchDocContent = async (id) => {
      try {
        const ebookId = route.query.ebookId;
        if (!ebookId) {
          console.error("ebookId 未找到");
          return;
        }

        const response = await axios.get('/doc/document/content', {
          params: {
            ebookId: ebookId,
            id: id
          }
        });

        return response.data.content.content;
      } catch (error) {
        console.error('Failed to fetch document content:', error);
        return '';
      }
    };

    const showEditModal = (doc) => {
      editForm.value = {
        ...doc,
      };
      editModalTitle.value = '编辑文档';
      editModalVisible.value = true;
    };

    const editDoc = async (id) => {
      console.log('开始编辑文档,id:', id);

      const doc = findDoc(docTree.value, id);
      console.log('找到的文档:', doc);

      const content = await fetchDocContent(id);
      console.log('获取到的文档内容:', content);

      doc.content = content;
      console.log('设置文档内容后的文档:', doc);

      showEditModal(doc);
      console.log('显示编辑框');
    };

    const findDoc = (categories, id) => {
      for (const doc of categories) {
        if (doc.id === id) {
          return doc;
        }
        if (doc.children) {
          const foundDoc = findDoc(doc.children, id);
          if (foundDoc) {
            return foundDoc;
          }
        }
      }
      return null;
    };

    const deleteDoc = async (id) => {
      try {
        await axios.delete(`/doc/delete/${id}`);
        fetchData();
      } catch (error) {
        console.error('Delete failed:', error);
      }
    };

    const handleEditOk = () => {
      editFormRef.value
          .validate()
          .then(async () => {
            const ebookId = route.query.ebookId;
            if (!ebookId) {
              console.error("ebookId 未找到");
              return;
            }

            editForm.value.ebookId = ebookId;

            try {
              console.log(editForm.value, 'editForm.value');
              await axios.post('/doc/save', editForm.value);
              editModalVisible.value = false;
              fetchData();
            } catch (error) {
              console.error('Save failed:', error);
            }
          })
          .catch((error) => {
            console.error('Validate failed:', error);
          });
    };

    const handleModalCancel = () => {
      editModalVisible.value = false;
    };

    onMounted(() => {
      fetchData();
    });

    return {
      displayCategories,
      docTree,
      searchText,
      editModalVisible,
      editModalTitle,
      editForm,
      editFormRef,
      editFormRules,
      fieldNames,
      handleSearch,
      addDoc,
      editDoc,
      deleteDoc,
      handleEditOk,
      handleModalCancel,
    };
  },
});
</script>

<style scoped>
.doc-management {
  max-width: 800px;
  margin: 0 auto;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-input {
  max-width: 300px;
}

.add-button {
  margin-left: 10px;
}

.content {
  border: 1px solid #ccc;
  border-radius: 4px;
  padding: 20px;
}

.doc-name {
  margin-right: 10px;
}

.actions {
  display: inline-block;
}
</style>